package zhongbo.java.air.websocet;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.locationtech.jts.geom.Coordinate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import zhongbo.java.air.Util.JtsUtil;
import zhongbo.java.air.dictionary.mapper.ZoneMapper;
import zhongbo.java.air.dictionary.model.Zone;
import zhongbo.java.air.dto.PointDto;
import zhongbo.java.air.mapper.AirAlertLogMapper;
import zhongbo.java.air.model.AlertLog;
import zhongbo.java.air.model.FlightPathl;
import zhongbo.java.air.service.impl.JtsServiceImpl;

import javax.websocket.CloseReason;
import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName AlertZoneWebSocket
 * @Description TODO
 * @Author 红
 * @Date 2025/4/9 11:11
 */
@ServerEndpoint(value = "/websocket/alert")
@Component
@Slf4j
public class AlertZoneWebSocket {
    @Autowired
    private ZoneMapper zoneMapper;
    @Autowired
    private AirAlertLogMapper logMapper;
    @Autowired
    private JtsServiceImpl jtsService;
    private static final Map<String, Session> sessionMap = new HashMap<>();

    @OnOpen
    public void open(Session session) {
        String sessionId = session.getId();
        System.out.println("建立连接：id：" + sessionId);
        sessionMap.put(sessionId, session);

    }

    @OnClose
    public void close(Session session, CloseReason reason) {
        String closeId = session.getId();
        String reasonPhrase = reason.getReasonPhrase();
        System.out.println("关闭ws连接: {}, reason: {}" + closeId + reasonPhrase);
        sessionMap.remove(closeId, session);
    }

    // 广播所以客户端
    public void broadcastMessage(String message) {
        sessionMap.values().forEach(session -> {
            System.out.println("收到ws的消息:" + message);
            if (session.isOpen()) {
                try {
                    session.getBasicRemote().sendText(message);

                } catch (IOException e) {
                    log.error("广播消息发生异常: {}", e.getMessage());
                }
            }
        });

    }


    public void selectZone(FlightPathl flightPath) {
        List<Zone> zoneList = zoneMapper.selectList(null);
        if (zoneList.isEmpty()) {
            System.out.println("No alert zones found. Ending alert check.");
            return;
        }
        // 查询 5 分钟内的告警日志记录
        LocalDateTime fiveMinutesAgo = LocalDateTime.now().minusMinutes(1);
        QueryWrapper<AlertLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("icao_code", flightPath.getIcaoCode());
        queryWrapper.ge("trigger_time", Timestamp.valueOf(fiveMinutesAgo));
        queryWrapper.last("LIMIT 1"); // 限制只返回一条记录
        AlertLog quer = logMapper.selectOne(queryWrapper);
        if (quer != null) {

            return;
        }

        for (Zone zone : zoneList) {
            List<PointDto> pointList = jtsService.parseAlertZoneVertices(zone.getVertices());
            //根据经纬度创建点位
            if (pointList != null && jtsService.isInAlertZone(pointList, flightPath.getLongitude(), flightPath.getLatitude())) {
                // 构建告警日志记录并保存入库
                AlertLog alertLog = new AlertLog();
                alertLog.setIcaoCode(flightPath.getIcaoCode());
                alertLog.setTriggerTime(new Timestamp(flightPath.getTimestamp().getTime()));
                alertLog.setAlertZoneId(zone.getId());
                alertLog.setAlertType(zone.getZoneType());
                Coordinate coordinate = JtsUtil.createCoordinate(flightPath.getLongitude(), flightPath.getLatitude());
                ObjectMapper objectMapper = new ObjectMapper();
                String coorJson = null;
                try {
                    coorJson = objectMapper.writeValueAsString(coordinate);
                    alertLog.setTriggerCoordinates(coorJson);
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
                logMapper.insert(alertLog);
                // 广播告警日志记录到所有在线用户
                String jsonMassage = JSONUtil.toJsonStr(alertLog);
                broadcastMessage(jsonMassage);
            }

        }
    }


}

